<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight dense>
    <AdVxeTable @register="registerTable">
      <template #tools>
        <Authority :value="'Root.Admin.Identity.User.Create'">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />{{
              t('routes.system.identity.user.addUser')
            }}
          </a-button>
        </Authority>
        <Authority :value="'Root.Admin.Identity.User.Create'">
          <ImpExcel @success="handleImport">
            <a-button type="primary">
              <Icon icon="feather:download" />{{ t('common.importText') }}
            </a-button>
          </ImpExcel>
        </Authority>
        <a-button type="primary" @click="handleExport">
          <Icon icon="feather:upload" />{{ t('common.exportText') }}
        </a-button>
      </template>
      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Admin.Identity.User.Delete', // 权限控制
              ifShow: (_action) => {
                return row?.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
          :dropDownActions="[
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Admin.Identity.User.Update', // 权限控制
              ifShow: (_action) => {
                return row?.Updatable === true; // 根据业务控制是否显示: 是否可更新的数据权限状态
              },
              onClick: handleEdit.bind(null, row),
            },
            {
              icon: 'carbon:user-role',
              label: t('routes.system.identity.role.title'),
              auth: ['Root.Admin.Identity.Role.ReadUserRoles'], // 权限控制
              onClick: handleSetRolesModalOpen.bind(null, row),
            },
            {
              icon: 'clarity:organization-line',
              label: t('routes.system.identity.organization.title'),
              auth: ['Root.Admin.Identity.Organization.ReadUserOrganizations'], // 权限控制
              onClick: handleSetOrganizationsModalOpen.bind(null, row),
            },
            {
              icon: 'ant-design:safety-certificate-outlined',
              label: t('routes.system.identity.permissionText'),
              auth: ['Root.Admin.Auth.Module.ReadUserModules'], // 权限控制
              onClick: handleModuleDrawerOpen.bind(null, row),
            },
            {
              icon: 'ant-design:security-scan-outlined',
              label: t('routes.system.identity.viewFunctionText'),
              auth: 'Root.Admin.Auth.UserFunction.ReadFunctions', // 权限控制
              onClick: handleReadFunctions.bind(null, row),
            },
          ]"
        />
      </template>
    </AdVxeTable>

    <!-- <TreeModal
      @register="registerSetUserRolesModal"
      :title="t('routes.system.identity.role.title')"
      :toolbar="true"
      :search="true"
      :checkable="true"
      :closeFunc="handleSetUserRolesModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.User.SetRoles'"
      :okFunc="handleSetUserRolesModalOk"
    /> -->
    <UserRoleModal
      @register="registerSetRolesModal"
      :title="t('routes.system.identity.role.title')"
      :search="true"
      :closeFunc="handleSetRolesModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.User.SetRoles'"
      :okFunc="handleSetRolesModalOk"
      width="50%"
    />
    <TreeDrawer
      @register="registerModuleDrawer"
      :title="t('routes.system.identity.permissionText')"
      :toolbar="true"
      :search="true"
      :checkable="true"
      :closeFunc="handleModuleDrawerClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.User.SetModules'"
      :okFunc="handleModuleDrawerOk"
      width="70%"
    />
    <UserFunctionDrawer
      @register="registerUserFunctionDrawer"
      :title="t('routes.system.identity.user.userFunctions')"
    />
    <UserOrganizationTransferModal
      @register="registerSetOrganizationsModal"
      :title="t('routes.system.identity.organization.title')"
      :search="true"
      :closeFunc="handleSetOrganizationsModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.User.SetOrganizations'"
      :okFunc="handleSetOrganizationsModalOk"
      width="50%"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { h, ref } from 'vue';
  import { Authority } from '@/components/Authority';
  import { useI18n } from '@/hooks/web/useI18n';
  import { PageWrapper } from '@/components/Page';
  import { AdVxeTable, useAdVxeTable, TableAction } from '@/components/AdVxeTable';
  import { jsonToSheetXlsx, ImpExcel, ExcelData } from '@/components/Excel';
  import { useMessage } from '@/hooks/web/useMessage';
  import { isString } from '@/utils/is';

  import {
    readUsers,
    createUsers,
    updateUsers,
    deleteUsers,
    setUserRoles,
    setUserOrganizations,
    setUserModules,
  } from '@/api/identity/admin/user';
  import { readUserRoles } from '@/api/identity/admin/role';
  import { readUserOrganizations } from '@/api/identity/admin/organization';
  import { readUserModules } from '@/api/authorization/admin/module';
  import { FormModeEnum } from '@/enums/formEnum';

  import Icon from '@/components/Icon/Icon.vue';

  import { columns, makeUserModulesTree } from './user.data';

  import { useModal } from '@/components/AdVxeModal';
  import { TreeItem, TreeActionType } from '@/components/Tree';

  import { TreeDrawer } from '@/components/ViewModal';

  import { useDrawer } from '@/components/Drawer';
  import UserFunctionDrawer from './UserFunctionDrawer.vue';

  import RoleTransferModal from '../role/RoleTransferModal.vue';
  import OrganizationTransferModal from '@/views/system/identity/organization/OrganizationTransferModal.vue';

  const UserRoleModal = RoleTransferModal;
  const UserOrganizationTransferModal = OrganizationTransferModal;

  defineOptions({ name: 'UserPage' });

  const { t } = useI18n();
  const { createConfirm, createMessage } = useMessage();

  const loadingRef = ref(false);
  function openWrapLoading() {
    loadingRef.value = true;
  }
  function closeWrapLoading() {
    loadingRef.value = false;
  }

  const [registerTable, { getTable, openDetailForm, reload }] = useAdVxeTable({
    id: 'system-user-page-table',
    // 表标题呈现器
    title: t('routes.system.identity.user.userList'),
    // 表格数据接口请求对象
    api: readUsers,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'identity_user_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('routes.system.identity.user.title'),
      position:{
        top: 50
      },
      // 实体新增接口请求对象
      createApi: createUsers,
      // 实体更新接口请求对象
      updateApi: updateUsers,  
    },
    // 表单列信息 AdColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 排序配置项 multiple-多字段排序 chronological-按点击先后顺序排序
    sortConfig: { multiple: true, chronological: true },
    // 表格右侧操作列配置
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  /** 处理创建 */
  async function handleCreate() {
    openDetailForm(FormModeEnum.Add);
  }

  /** 处理编辑 */
  async function handleEdit(record: any) {
    openDetailForm(FormModeEnum.Edit, record);
  }

  /** 处理删除 */
  async function handleDelete(record: any) {
    // console.log(record);
    const ajaxResult = await deleteUsers([record.Id]);
    if (ajaxResult.Succeeded) {
      createMessage.success(t('common.successText'));
      reload();
    }
  }

  //#region "设置用户角色-树形（注释备查）"
  // const [registerSetUserRolesModal, setUserRolesModalMethods] = useModal();
  // /** 处理打开设置用户角色弹窗 */
  // async function handleSetUserRolesModalOpen(record: Recordable) {
  //   if (record && record.Id) {
  //     const userRoleNodes = await readUserRoles(record.Id);
  //     const treeItems: TreeItem[] = [];
  //     const checkedKeys: (string | bigint)[] = [];
  //     if (userRoleNodes && userRoleNodes.length > 0) {
  //       userRoleNodes.forEach((item) => {
  //         treeItems.push({
  //           icon: 'carbon:user-role',
  //           key: item.Id,
  //           title: item.Name,
  //         });
  //         if (item.IsChecked) {
  //           checkedKeys.push(item.Id);
  //         }
  //       });
  //     }

  //     setUserRolesModalMethods.openModal(true, {
  //       treeData: treeItems,
  //       // checkedKeys: userRoleNodes.filter((m) => m.IsChecked === true),
  //       checkedKeys: checkedKeys,
  //       record: record,
  //     });
  //     setUserRolesModalMethods.setModalProps({
  //       title: `${t('routes.system.identity.role.title')} - ${record.UserName}`,
  //     });
  //   }
  // }
  // /** 处理设置用户角色弹窗关闭按钮 */
  // async function handleSetUserRolesModalClose() {
  //   return true;
  // }
  // /** 处理设置用户角色弹窗确定按钮 */
  // async function handleSetUserRolesModalOk(record: any, treeRef: Nullable<TreeActionType>) {
  //   if (treeRef && record && record.Id) {
  //     const checkedKeys = treeRef.getCheckedKeys();
  //     if (checkedKeys) {
  //       // console.log(checkedKeys);
  //       const roleIds = checkedKeys as (string | bigint)[];
  //       const ajaxResult = await setUserRoles({ UserId: record.Id, RoleIds: [...roleIds] });
  //       if (ajaxResult.Succeeded) {
  //         if (ajaxResult.Content) {
  //           createMessage.success(ajaxResult.Content);
  //         }
  //         reload();
  //         return true;
  //       } else {
  //         return false;
  //       }
  //     }
  //     return true;
  //   } else {
  //     return true;
  //   }
  // }
  //#endregion
  //#region "设置用户角色-弹窗穿梭框"
  const [registerSetRolesModal, setRolesModalMethods] = useModal();
  /** 处理打开设置用户角色弹窗 */
  async function handleSetRolesModalOpen(record: any) {
    if (record && record.Id) {
      const roleNodes = await readUserRoles(record.Id);

      setRolesModalMethods.openModal(true, {
        roleNodes: roleNodes,
        record: record,
      });
      setRolesModalMethods.setModalProps({
        title: `${t('routes.system.identity.role.title')} - ${record.UserName}`,
      });
    }
  }
  /** 处理设置用户角色弹窗关闭按钮 */
  async function handleSetRolesModalClose() {
    return true;
  }
  /** 处理设置用户角色弹窗确定按钮 */
  async function handleSetRolesModalOk(
    targetKeys: (string | bigint)[],
    roleNodes: any[],
    record: any,
  ) {
    if (targetKeys && roleNodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const roleIds = checkedKeys;
        const ajaxResult = await setUserRoles({ UserId: record.Id, RoleIds: [...roleIds] });
        if (ajaxResult.Succeeded) {
          createMessage.success(t('common.successText'));
          reload();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion

  //#region "设置用户权限-抽屉模式"
  const [registerModuleDrawer, moduleDrawerMethods] = useDrawer();
  /** 处理打开设置权限抽屉 */
  async function handleModuleDrawerOpen(record: any) {
    if (record && record.Id) {
      loadingRef.value = true;
      try {
        const userModules = await readUserModules(record.Id);
        let treeItems: TreeItem[] = [];
        let checkedKeys: string[] = [];
        treeItems = makeUserModulesTree(userModules, checkedKeys);
        // console.log('SetUserModules', { userModules, checkedKeys, treeItems });
        moduleDrawerMethods.openDrawer(true, {
          treeData: treeItems,
          checkedKeys: checkedKeys,
          record: record,
        });
        moduleDrawerMethods.setDrawerProps({
          title: `${t('routes.system.identity.permissionText')} - ${record.UserName}`,
        });
      } finally {
        loadingRef.value = false;
      }
    }
  }
  /** 处理设置权限抽屉关闭按钮 */
  async function handleModuleDrawerClose() {
    return true;
  }
  /** 处理设置权限抽屉确定按钮 */
  async function handleModuleDrawerOk(record: any, treeRef: TreeActionType | null) {
    if (treeRef && record && record.Id) {
      const checkedKeys = treeRef.getCheckedKeys();
      if (checkedKeys) {
        // console.log(checkedKeys);
        const moduleIds = checkedKeys as unknown as (string | bigint)[];
        const ajaxResult = await setUserModules({
          UserId: record.Id,
          ModuleIds: [...moduleIds],
        });
        if (ajaxResult.Succeeded) {
          createMessage.success(t('common.successText'));
          reload();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion

  //#region "处理读取用户功能"
  const [registerUserFunctionDrawer, userFunctionDrawerMethods] = useDrawer();
  /** 处理读取用户功能 */
  async function handleReadFunctions(record: any) {
    userFunctionDrawerMethods.openDrawer(true, {
      userId: record.Id,
    });
    userFunctionDrawerMethods.setDrawerProps({
      title: `${t('routes.system.identity.user.userFunctions')} - ${record.UserName}`,
    });
  }
  //#endregion

  //#region "设置组织"
  const [registerSetOrganizationsModal, setOrganizationsModalMethods] = useModal();
  /** 处理打开设置组织机构弹窗 */
  async function handleSetOrganizationsModalOpen(record: any) {
    const orgNodes = await readUserOrganizations(record.Id);
    // console.log('handleSetOrganizationsModalOpen', orgNodes);
    setOrganizationsModalMethods.openModal(true, {
      organizationNodes: orgNodes,
      record: record,
    });
    setOrganizationsModalMethods.setModalProps({
      title: `${t('routes.system.identity.organization.title')} - ${record.UserName}`,
    });
  }
  /** 处理设置组织机构弹窗关闭按钮 */
  async function handleSetOrganizationsModalClose() {
    return true;
  }
  /** 处理设置组织机构弹窗确定按钮 */
  async function handleSetOrganizationsModalOk(
    targetKeys: (string | bigint)[],
    nodes: any[],
    record: any,
  ) {
    if (targetKeys && nodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const userOrganizations: any[] = [];
        checkedKeys.forEach((item) => {
          userOrganizations.push({
            OrganizationId: item,
            Administrator: false,
            Leader: false,
          });
        });
        const ajaxResult = await setUserOrganizations({
          UserId: record.Id as string,
          UserOrganizations: [...userOrganizations],
        });
        if (ajaxResult.Type === 200) {
          createMessage.success(t('common.successText'));
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion

  function getTableData() {
    const $table = getTable();
    let tableData: any[] = [];
    if ($table) {
      tableData = $table.getTableData()?.tableData || [];
    }
    return tableData;
  }

  /** 处理导入 */
  async function handleImport(record: ExcelData[]) {
    // console.log(record);
    // let tableList: any[] = [];
    // for (const excelData of record) {
    //   const {
    //     header,
    //     results,
    //     meta: { sheetName },
    //   } = excelData;
    //   const columns: any[] = [];
    //   for (const title of header) {
    //     columns.push({ title, dataIndex: title });
    //   }
    //   tableList.push({ title: sheetName, dataSource: results, columns });
    // }
    if (record[0]) {
      const { results } = record[0];
      createConfirm({
        zIndex: 999999999,
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('common.importConfirmText')),
        onOk: async () => {
          try {
            openWrapLoading();
            const dtos: any[] = results.map((item) => {
              let dto: { [key: string]: any } = {};
              for (const key in item) {
                if (Object.prototype.hasOwnProperty.call(item, key)) {
                  // console.log(item[key], key);
                  const field = columns.filter((o) => o.title === key)[0]?.field;
                  let value = item[key];
                  if (isString(value)) {
                    value = value?.replace(/\s+/g, '');
                  }
                  dto[field || key] = value || undefined;
                }
              }
              return dto;
            });
            const ajaxResult = await createUsers(dtos);
            if (ajaxResult.Succeeded) {
              createMessage.success(t('common.successText'));
              await reload();
            }
          } finally {
            closeWrapLoading();
          }
        },
      });
    }
  }
  /** 处理导出 */
  function handleExport() {
    try {
      openWrapLoading();
      const tableData: any[] = getTableData().map((item) => {
        return {
          Id: item.Id, // 用户编号
          UserName: item.UserName, // 用户名
          NickName: item.NickName, // 用户昵称
          Email: item.Email, // 电子邮箱
          EmailConfirmed: item.EmailConfirmed, // 邮箱是否已确认
          PhoneNumber: item.PhoneNumber, // 手机号码
          PhoneConfirmed: item.PhoneConfirmed, // 手机是否已确认
          // Avatar: item.Avatar,  // 电子头像
          // Signature: item.Signature,  // 电子签名
          Gender: item.Gender, // 性别
          Birthday: item.Birthday, // 生日
          BloodType: item.BloodType, // 血型
          // Tag: item.Tag, // 标签
          // Title: item.Title, // 头衔
          Address: item.Address, // 地址
          Profile: item.Profile, // 简介
          Sign: item.Sign, // 个性签名
          Remark: item.Remark, // 备注
          HomePath: item.HomePath, // 主页
          Password: item.Password, // 密码
          LockoutEnabled: item.LockoutEnabled, // 是否启用登录锁
          IsLocked: item.IsLocked, // 是否锁定
        };
      });
      let tableHeader: { [key: string]: any } = {};
      for (const key in tableData[0]) {
        if (Object.prototype.hasOwnProperty.call(tableData[0], key)) {
          // console.log(tableData[0][key], key);
          tableHeader[key] = columns.filter((o) => o.field === key)[0]?.title;
        }
      }
      jsonToSheetXlsx({
        data: tableData,
        header: tableHeader,
        filename: `${t('用户')}.xlsx`,
        sheetName: t('用户'),
      });
    } finally {
      closeWrapLoading();
    }
  }
</script>
